package toOffer;

/**
 * @author YuanAo
 * @date 2024/6/26 15:13
 * @description 训练计划II
 */

/**
 * 题目：给定一个头节点为 head 的链表用于记录一系列核心肌群训练项目编号，请查找并返回倒数第 cnt 个训练项目编号。
 * 示例 1：
 * 输入：head = [2,4,7,8], cnt = 1
 * 输出：8
 */
public class LCR140 {
    public static void main(String[] args) {
        int[] ints = {2, 4, 7, 8};
        ListNode listNode = new ListNode();
        for (int i = ints.length - 1; i >= 0; i--) {
            if (i == ints.length - 1){
                listNode = new ListNode(ints[i]);
            }else {
                listNode = new ListNode(ints[i], listNode);
            }
        }
        int cnt = 1;
        System.out.println(trainingPlan(listNode, cnt).getVal());
    }

    public static ListNode trainingPlan(ListNode head, int cnt) {
        ListNode left = head;
        ListNode right = left;
        while (cnt - 1 != 0){
            right = right.next;
            cnt--;
        }

        while (right.next != null){
            left = left.next;
            right = right.next;
        }

        return left;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        public int getVal() {
            return val;
        }

        public void setVal(int val) {
            this.val = val;
        }

        public ListNode getNext() {
            return next;
        }

        public void setNext(ListNode next) {
            this.next = next;
        }
    }
}
